package logic

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"group-card/common/constant"
	"group-card/common/tool"
	"group-card/model/entity"
	"group-card/rpc/card/cardclient"
	"group-card/rpc/card/internal/svc"
)

type PublishAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPublishAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishAddLogic {
	return &PublishAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PublishAddLogic) PublishAdd(in *cardclient.PublishAddRequest) (*cardclient.PublishAddResponse, error) {

	has, err := l.svcCtx.PublishModel.IsExist("service_number = ?", in.ServiceNumber)
	if err != nil {
		return nil, err
	}
	if has {
		return nil, errors.New("银行消费券号已存在")
	}

	data := &entity.CardPublishReq{
		AdminId:            in.AdminId,
		CustomerId:         in.CustomerId,
		SkinId:             in.SkinId,
		Count:              in.Count,
		BeginNumber:        in.BeginNumber,
		EndNumber:          in.EndNumber,
		Status:             constant.CardPublishStatus10,
		Type:               in.Type,
		ServiceNumber:      in.ServiceNumber,
		ServiceOrderNumber: tool.GenerateForOrderNo(),
		ServiceMoney:       in.ServiceMoney,
	}

	var ctx context.Context
	lastInsertId, err := l.svcCtx.PublishModel.Insert(ctx, data)
	if err != nil {
		return nil, err
	}

	return &cardclient.PublishAddResponse{Id: lastInsertId}, nil
}
